﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Configuration;
using MySql.Data.MySqlClient;
using ExifToolWrap;

namespace PhotoRank
{
    /// <summary>
    /// Summary description for UploadHandler
    /// </summary>
    public class UploadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";

            HttpPostedFile file = context.Request.Files["Filedata"];
            string uploadPath =
                HttpContext.Current.Server.MapPath(@context.Request["folder"]);

            if (file != null)
            {
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }
                string filename = DateTime.Now.Ticks.ToString() + "_" + file.FileName;
                string fullpatch = uploadPath + "\\" + filename;
                file.SaveAs(fullpatch);

                //下面这句代码缺少的话，上传成功后上传队列的显示不会自动消失
                context.Response.Write("1");
                ExifToolWrapper ExifInfo = new ExifToolWrapper();
                ExifInfo.SaveExifData_Web(fullpatch, uploadPath + "\\");
                InsertDB(filename, fullpatch, file, ExifInfo);

            }
            else
            {
                context.Response.Write("0");
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        public void InsertDB(string filename, string fullpatch, HttpPostedFile file, ExifToolWrapper ExifInfo)
        {
            int ID;
            MySql.Data.MySqlClient.MySqlConnection DBConn = new MySql.Data.MySqlClient.MySqlConnection();
            string connString = ConfigurationManager.ConnectionStrings["photorankConnectionString"].ToString();
            DBConn.ConnectionString = connString;
            DBConn.Open();

            string sqlstr = "insert into Photo (filename,title,patchfull,eolnumber,rate,User_id,filename_orignal) values(?filename,?title,?patchfull,?eolnumber,?rate,?User_id,?filename_orignal); SELECT LAST_INSERT_ID();";
            //  MySqlCommand cmd = new MySqlCommand("SELECT * FROM `User` WHERE UserName = ?UserName AND Password = ?Password LIMIT 1");
            //cmd.Connection = conn;
            MySqlCommand command = new MySqlCommand(sqlstr, DBConn);

            command.Parameters.AddWithValue("title", "null");
            command.Parameters.AddWithValue("filename", filename);
            command.Parameters.AddWithValue("filename_orignal", file.FileName);
            command.Parameters.AddWithValue("patchfull", fullpatch);
            command.Parameters.AddWithValue("eolnumber", 1200);
            command.Parameters.AddWithValue("rate", 3);
            command.Parameters.AddWithValue("User_id", 1);// should be update to the user id .
          //  command.ExecuteNonQuery();

            ID = Convert.ToInt32(command.ExecuteScalar());
            String[] StringArray;

            StringArray = new String[5];
            StringArray[0] = "iso";
            StringArray[1] = "focal_length";
            StringArray[2] = "exposure_time";
            StringArray[3] = "f_number";




            string sqlstr1 = "insert into photoexif (";
            string sqlstr2 = " values(";
            sqlstr1 = sqlstr1 + "id,";
            sqlstr2 = sqlstr2 + ID + ",";

            bool IsExif = false;

            foreach (var item in ExifInfo)
            {
                string itemname_change = item.name.ToString().ToLower().Replace(" ", "_").Replace("/", "_").Replace("-", "_");

                foreach (string exifstring in StringArray)
                {
                    if (itemname_change == exifstring)
                    {
                        sqlstr1 = sqlstr1 + itemname_change + ",";
                        sqlstr2 = sqlstr2 + "'" + item.value.ToString() + "'" + ",";
                        IsExif = true;
                    }

                }

            }
            sqlstr1 = sqlstr1.Substring(0, sqlstr1.Length - 1);
            sqlstr2 = sqlstr2.Substring(0, sqlstr2.Length - 1);
            sqlstr1 = sqlstr1 + ")";
            sqlstr2 = sqlstr2 + ");";
            sqlstr = sqlstr1 + sqlstr2;

            if (IsExif)
            {
                command = new MySqlCommand(sqlstr, DBConn);
                command.ExecuteNonQuery();
            }
            DBConn.Close();

        }
    }
}